package com.ruoyi.stock2.thread.aboutDownloadData;

import java.io.*;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.jsoup.Jsoup;
import org.jsoup.Connection.Response;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;

import com.ruoyi.stock2.domain.TRADEDATA;
import com.ruoyi.stock2.utils.DateUtils2;

public class CheckSourceReady1 {
	
	private static boolean truefalse = true;
	
	public static String checkSourceReady() {
		SimpleDateFormat sFormat = new SimpleDateFormat("yyyy-MM-dd");
		Date date = new Date();
		String endDate = sFormat.format(date);
		String jidu = String.valueOf((Integer.valueOf(sFormat.format(date).split("-")[1])-1)/3+1);
		String sinatime = "";
		List<String> l = new ArrayList<String>();
		
		l.add("603318");
		l.add("002569");
		l.add("000001");
		l.add("000002");
		l.add("000004");
		l.add("000061");
		
		/*
		 * 
			http://quotes.money.163.com/service/chddata.html?code=1000001&start=20140101&end=20191209&fields=TCLOSE;HIGH;LOW;TOPEN;LCLOSE;CHG;PCHG;TURNOVER;VOTURNOVER;VATURNOVER;TCAP;MCAP
			http://quotes.money.163.com/trade/lsjysj_zhishu_399001.html?year=2020&season=4
			http://quotes.money.163.com/trade/lsjysj_000001.html?year=2020&season=4
					 */
		
		for(int i = 0 ; i<l.size();i++){
			truefalse = true;
			while(truefalse){
				String temp = checkSourceReady("http://quotes.money.163.com/trade/lsjysj_"+l.get(i)+".html?year="+sFormat.format(date).split("-")[0]+"&season="+jidu, endDate);
				if(temp.compareTo(sinatime)>0){
					sinatime = temp;
				}
				
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			
		}
		return sinatime;
	} 
	
	public static String checkSourceReady(String httpstr, String endDate ) {
	    String sinatime = "";
		Document doc;
		try {
			
			doc = Jsoup.connect(httpstr).timeout(10000).get();
			Element e = doc.getElementsByClass("table_bg001 border_box limit_sale").get(0)
					.getElementsByTag("tbody").get(0)
					.getElementsByTag("tr").get(0)
					.getElementsByTag("td").get(0);
					
			
			System.out.println(doc.getElementsByClass("table_bg001 border_box limit_sale").get(0)
					.getElementsByTag("tbody").get(0)
					.getElementsByTag("tr").get(0)
					.getElementsByTag("td"));
			sinatime = e.text();
			truefalse = false;
		}catch (java.net.SocketTimeoutException e1) {
			e1.printStackTrace();
		}catch (java.net.UnknownHostException e1) {
			e1.printStackTrace();
		}catch (Exception e1) {
			e1.printStackTrace();
		}finally{
			truefalse = false;
		}
			
		return sinatime;
	}
	
	//请求下载数据，返回数据流
	private static void downloadData(String symbol, String lastDownLoadDateFromSina, String nowDate) {
		String code = "1"+symbol;;
		if("999001".equals(symbol)) {
			code = "1399001";
		}
		if("900001".equals(symbol)) {
			code = "0000001";
		}
		if("999006".equals(symbol)) {
			code = "1399102";
		}
		if(symbol.startsWith("6")) {
			code = "0"+symbol;
		}
		BufferedReader bufferedReader = null;
		
		try {
			
			Response resultImageResponse = Jsoup.connect("http://quotes.money.163.com/service/chddata.html?code="+code+"&start="+lastDownLoadDateFromSina+"&end="+nowDate+"&fields=TCLOSE;HIGH;LOW;TOPEN;LCLOSE;CHG;PCHG;TURNOVER;VOTURNOVER;VATURNOVER;TCAP;MCAP")
					.ignoreContentType(true)
					.execute();
			
			bufferedReader = new BufferedReader(new InputStreamReader(resultImageResponse.bodyStream(), "GBK"));
            String s;
           /*
            * 日期	股票代码	名称	收盘价	最高价	最低价	开盘价	前收盘	涨跌额	涨跌幅	换手率	成交量	成交金额	总市值	流通市值	成交笔数
			2019/9/10	'399102	创业板综	2060.6597	2068.2884	2046.2912	2066.6962	2063.7882	-3.1285	-0.1516		10976119782	1.49E+11			8201387
			2019/9/9	'399102	创业板综	2063.7882	2063.7882	2012.9203	2023.4389	2007.3455	56.4427	2.8118		11239712033	1.53E+11			8089390
            */
            bufferedReader.readLine();
            List<TRADEDATA> emps = new ArrayList<TRADEDATA>(100);
            while ((s = bufferedReader.readLine()) != null) {
                String[] e = s.split(",");
                if(!"None".equals(e[8]) && !"None".equals(e[9]) && !"0.0".equals(e[3])) {
                	TRADEDATA tradeData = new TRADEDATA();
    				tradeData.setDatetime(DateUtils2.formatStringToDate(e[0], "yyyy-MM-dd"));
    				tradeData.setSymbol(symbol);
    				tradeData.setDateopenprice(new BigDecimal(e[6]));
    				tradeData.setCloseprice(new BigDecimal(e[3]));
    				tradeData.setLowprice(new BigDecimal(e[5]));
    				tradeData.setHighprice(new BigDecimal(e[4]));
    				tradeData.setAmount(new BigDecimal(e[11]).divide(new BigDecimal(10000), 0, BigDecimal.ROUND_HALF_UP));
    				tradeData.setVolume(new BigDecimal(e[12]).divide(new BigDecimal(100), 0, BigDecimal.ROUND_HALF_UP));
//    				TRADEDATA key = new TRADEDATA(symbol, tradeData.getDatetime());
//    				List<TRADEDATA> tradeData1 = tradedataMapper.selectTRADEDATAList(key);
//    				if(tradeData1.size() != 0) {
//    					tradedataMapper.updateTRADEDATA(tradeData);
//    				}else {
    					emps.add(tradeData);
//    				}
                }
            }
            if(emps.size()>0) {
            	System.out.println("emps.size()="+emps.size());
            	Thread.sleep(5000);
            	emps.clear();
            }
            

		} catch (java.net.SocketTimeoutException e1) {
			e1.printStackTrace();
		} catch (Exception e1) {
			e1.printStackTrace();
		} finally {
			try {
				if(bufferedReader!=null) {
					bufferedReader.close();
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}


	private boolean downloadData5_31(String symbol, String lastDownLoadDateFromSina, String nowDate) {

		boolean nextf = false;

		String code = "1" + symbol;

		if ("999001".equals(symbol)) {
			code = "1399001";
		}
		if ("900001".equals(symbol)) {
			code = "0000001";
		}
		if ("999006".equals(symbol)) {
			code = "1399102";
		}
		if (symbol.startsWith("6")) {
			code = "0" + symbol;
		}
		BufferedReader bufferedReader = null;
		List<TRADEDATA> temp1 = new ArrayList<TRADEDATA>();
		List<TRADEDATA> concurrentLinkedQueue = new ArrayList<TRADEDATA>();

		try {
			Response resultImageResponse = Jsoup.connect("http://quotes.money.163.com/service/chddata.html?code=" + code + "&start=" + lastDownLoadDateFromSina + "&end=" + nowDate + "&fields=TCLOSE;HIGH;LOW;TOPEN;LCLOSE;CHG;PCHG;TURNOVER;VOTURNOVER;VATURNOVER;TCAP;MCAP")
					.ignoreContentType(true)
					.execute();

			bufferedReader = new BufferedReader(new InputStreamReader(resultImageResponse.bodyStream(), "GBK"));
			String s;
           /*
            * 日期	股票代码	名称	收盘价	最高价	最低价	开盘价	前收盘	涨跌额	涨跌幅	换手率	成交量	成交金额	总市值	流通市值	成交笔数
			2019/9/10	'399102	创业板综	2060.6597	2068.2884	2046.2912	2066.6962	2063.7882	-3.1285	-0.1516		10976119782	1.49E+11			8201387
			2019/9/9	'399102	创业板综	2063.7882	2063.7882	2012.9203	2023.4389	2007.3455	56.4427	2.8118		11239712033	1.53E+11			8089390
            */
			s=bufferedReader.readLine();
			while ((s = bufferedReader.readLine()) != null) {
				String[] e = s.split(",");
				if (!"None".equals(e[8]) && !"None".equals(e[9]) && !"0.0".equals(e[3])) {

					TRADEDATA tradeData = new TRADEDATA();
					if(e[0].contains("-")){
						tradeData.setDatetime(DateUtils2.formatStringToDate(e[0], "yyyy-MM-dd"));
					}else{
						tradeData.setDatetime(DateUtils2.formatStringToDate(e[0], "yyyyMMdd"));
					}
					tradeData.setSymbol(symbol);


					if (!"None".equals(e[3]) && !"0.0".equals(e[3]))
						tradeData.setCloseprice(new BigDecimal(e[3].replace(",", "")));
					else
						continue;
					if (!"None".equals(e[4]) && !"0.0".equals(e[4]))
						tradeData.setHighprice(new BigDecimal(e[4].replace(",", "")));
					else
						continue;
					if (!"None".equals(e[5]) && !"0.0".equals(e[5]))
						tradeData.setLowprice(new BigDecimal(e[5].replace(",", "")));
					else
						continue;
					if (!"None".equals(e[6]) && !"0.0".equals(e[6]))
						tradeData.setDateopenprice(new BigDecimal(e[6].replace(",", "")));
					else
						continue;


					if (!"None".equals(e[11]) && !"0.0".equals(e[11]))
						tradeData.setVolume(new BigDecimal(e[11].replace(",", "")).divide(new BigDecimal(100), 0, BigDecimal.ROUND_HALF_UP));
					else
						continue;

					if (!"None".equals(e[12]) && !"0.0".equals(e[12]))
						tradeData.setAmount(new BigDecimal(e[12].replace(",", "")).divide(new BigDecimal(10000), 0, BigDecimal.ROUND_HALF_UP));
					else
						continue;


					concurrentLinkedQueue.add(tradeData);



				}

			}

			if (concurrentLinkedQueue.size() > 0) {
				int sizec = concurrentLinkedQueue.size()-1;
				TRADEDATA obj = concurrentLinkedQueue.get(0);
				Date objdate = obj.getDatetime();
				String objdatetostrd = DateUtils2.formatDateToString(objdate,"yyyyMMdd");
				if(objdatetostrd.equals(nowDate)){
					nextf = true;
				}

			}


		} catch (java.net.SocketTimeoutException e1) {
			e1.printStackTrace();
		} catch (Exception e1) {
			e1.printStackTrace();
		} finally {
			try {
				if (bufferedReader != null) {
					bufferedReader.close();
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return nextf;
	}

	public static void main(String[] args) {
		//https://finance.yahoo.com/quote/002739.SZ/history?p=002739.SZ
		String url = "https://finance.yahoo.com/quote/002739.SZ/history?period1=1601424000&period2=1603843200&interval=1d&filter=history&frequency=1d&includeAdjustedClose=true";
		String url2 = "http://data.gtimg.cn/flashdata/hushen/daily/20/sz000004.js";
		//http://data.gtimg.cn/flashdata/hushen/daily/20/sh000001.js
		//http://data.gtimg.cn/flashdata/hushen/daily/20/sz399001.js
		//http://data.gtimg.cn/flashdata/hushen/daily/20/sz399006.js
		//Document doc;

		BufferedReader bufferedReader = null;

		try {
			Response resultImageResponse = Jsoup.connect(url2)
					.ignoreContentType(true)
					.execute();

			bufferedReader = new BufferedReader(new InputStreamReader(resultImageResponse.bodyStream(), "GBK"));
           /*
            * 日期	股票代码	名称	收盘价	最高价	最低价	开盘价	前收盘	涨跌额	涨跌幅	换手率	成交量	成交金额	总市值	流通市值	成交笔数
			2019/9/10	'399102	创业板综	2060.6597	2068.2884	2046.2912	2066.6962	2063.7882	-3.1285	-0.1516		10976119782	1.49E+11			8201387
			2019/9/9	'399102	创业板综	2063.7882	2063.7882	2012.9203	2023.4389	2007.3455	56.4427	2.8118		11239712033	1.53E+11			8089390
            */
			String s =bufferedReader.readLine();


			//doc = Jsoup.connect(url2).timeout(10000).get();
			while ((s = bufferedReader.readLine()) != null) {
				System.out.println(s);
			}



		}catch (java.net.SocketTimeoutException e1) {
			e1.printStackTrace();
		}catch (java.net.UnknownHostException e1) {
			e1.printStackTrace();
		}catch (Exception e1) {
			e1.printStackTrace();
		}

	}
}
